import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { subscribeWithSelector } from 'zustand/middleware';

// UI 状态接口
interface UIState {
  // 主题相关
  theme: 'light' | 'dark' | 'system';

  // 侧边栏状态
  sidebarOpen: boolean;
  sidebarCollapsed: boolean;

  // 模态框状态
  modals: Record<string, boolean>;

  // 通知状态
  notifications: Notification[];

  // 加载状态
  globalLoading: boolean;
  loadingStates: Record<string, boolean>;

  // 错误状态
  errors: Record<string, string | null>;

  // 页面状态
  currentPage: string;
  breadcrumbs: Breadcrumb[];

  // 窗口状态
  windowFocused: boolean;
  windowVisible: boolean;
}

interface Notification {
  id: string;
  type: 'success' | 'error' | 'warning' | 'info';
  title: string;
  message?: string;
  duration?: number;
  timestamp: number;
}

interface Breadcrumb {
  label: string;
  path?: string;
  icon?: string;
}

// UI 操作接口
interface UIActions {
  // 主题操作
  setTheme: (theme: UIState['theme']) => void;
  toggleTheme: () => void;

  // 侧边栏操作
  setSidebarOpen: (open: boolean) => void;
  toggleSidebar: () => void;
  setSidebarCollapsed: (collapsed: boolean) => void;
  toggleSidebarCollapsed: () => void;

  // 模态框操作
  openModal: (modalId: string) => void;
  closeModal: (modalId: string) => void;
  toggleModal: (modalId: string) => void;
  closeAllModals: () => void;

  // 通知操作
  addNotification: (
    notification: Omit<Notification, 'id' | 'timestamp'>
  ) => void;
  removeNotification: (id: string) => void;
  clearNotifications: () => void;

  // 加载状态操作
  setGlobalLoading: (loading: boolean) => void;
  setLoading: (key: string, loading: boolean) => void;
  clearLoading: (key: string) => void;

  // 错误状态操作
  setError: (key: string, error: string | null) => void;
  clearError: (key: string) => void;
  clearAllErrors: () => void;

  // 页面状态操作
  setCurrentPage: (page: string) => void;
  setBreadcrumbs: (breadcrumbs: Breadcrumb[]) => void;
  addBreadcrumb: (breadcrumb: Breadcrumb) => void;

  // 窗口状态操作
  setWindowFocused: (focused: boolean) => void;
  setWindowVisible: (visible: boolean) => void;

  // 重置操作
  reset: () => void;
}

type UIStore = UIState & UIActions;

// 默认状态
const defaultState: UIState = {
  theme: 'system',
  sidebarOpen: true,
  sidebarCollapsed: false,
  modals: {},
  notifications: [],
  globalLoading: false,
  loadingStates: {},
  errors: {},
  currentPage: '/',
  breadcrumbs: [],
  windowFocused: true,
  windowVisible: true,
};

// 创建 UI store
export const useUIStore = create<UIStore>()(
  subscribeWithSelector(
    persist(
      (set, get) => ({
        ...defaultState,

        // 主题操作
        setTheme: theme => set({ theme }),
        toggleTheme: () => {
          const { theme } = get();
          const newTheme = theme === 'light' ? 'dark' : 'light';
          set({ theme: newTheme });
        },

        // 侧边栏操作
        setSidebarOpen: sidebarOpen => set({ sidebarOpen }),
        toggleSidebar: () =>
          set(state => ({ sidebarOpen: !state.sidebarOpen })),
        setSidebarCollapsed: sidebarCollapsed => set({ sidebarCollapsed }),
        toggleSidebarCollapsed: () =>
          set(state => ({
            sidebarCollapsed: !state.sidebarCollapsed,
          })),

        // 模态框操作
        openModal: modalId =>
          set(state => ({
            modals: { ...state.modals, [modalId]: true },
          })),
        closeModal: modalId =>
          set(state => ({
            modals: { ...state.modals, [modalId]: false },
          })),
        toggleModal: modalId =>
          set(state => ({
            modals: { ...state.modals, [modalId]: !state.modals[modalId] },
          })),
        closeAllModals: () => set({ modals: {} }),

        // 通知操作
        addNotification: notification => {
          const id = `notification_${Date.now()}_${Math.random()}`;
          const newNotification: Notification = {
            ...notification,
            id,
            timestamp: Date.now(),
          };

          set(state => ({
            notifications: [...state.notifications, newNotification],
          }));

          // 自动移除通知
          if (notification.duration !== 0) {
            const duration = notification.duration || 5000;
            setTimeout(() => {
              get().removeNotification(id);
            }, duration);
          }
        },
        removeNotification: id =>
          set(state => ({
            notifications: state.notifications.filter(n => n.id !== id),
          })),
        clearNotifications: () => set({ notifications: [] }),

        // 加载状态操作
        setGlobalLoading: globalLoading => set({ globalLoading }),
        setLoading: (key, loading) =>
          set(state => ({
            loadingStates: { ...state.loadingStates, [key]: loading },
          })),
        clearLoading: key =>
          set(state => {
            const { [key]: _, ...rest } = state.loadingStates;
            return { loadingStates: rest };
          }),

        // 错误状态操作
        setError: (key, error) =>
          set(state => ({
            errors: { ...state.errors, [key]: error },
          })),
        clearError: key =>
          set(state => {
            const { [key]: _, ...rest } = state.errors;
            return { errors: rest };
          }),
        clearAllErrors: () => set({ errors: {} }),

        // 页面状态操作
        setCurrentPage: currentPage => set({ currentPage }),
        setBreadcrumbs: breadcrumbs => set({ breadcrumbs }),
        addBreadcrumb: breadcrumb =>
          set(state => ({
            breadcrumbs: [...state.breadcrumbs, breadcrumb],
          })),

        // 窗口状态操作
        setWindowFocused: windowFocused => set({ windowFocused }),
        setWindowVisible: windowVisible => set({ windowVisible }),

        // 重置操作
        reset: () => set(defaultState),
      }),
      {
        name: 'ui-store',
        storage: createJSONStorage(() => localStorage),
        partialize: state => ({
          theme: state.theme,
          sidebarCollapsed: state.sidebarCollapsed,
        }),
      }
    )
  )
);

// 选择器
export const useTheme = () => useUIStore(state => state.theme);
export const useSidebar = () =>
  useUIStore(state => ({
    open: state.sidebarOpen,
    collapsed: state.sidebarCollapsed,
  }));
export const useModals = () => useUIStore(state => state.modals);
export const useNotifications = () => useUIStore(state => state.notifications);
export const useGlobalLoading = () => useUIStore(state => state.globalLoading);
export const useLoadingStates = () => useUIStore(state => state.loadingStates);
export const useErrors = () => useUIStore(state => state.errors);
export const useBreadcrumbs = () => useUIStore(state => state.breadcrumbs);
export const useWindowState = () =>
  useUIStore(state => ({
    focused: state.windowFocused,
    visible: state.windowVisible,
  }));

// 操作选择器
export const useUIActions = () =>
  useUIStore(state => ({
    setTheme: state.setTheme,
    toggleTheme: state.toggleTheme,
    setSidebarOpen: state.setSidebarOpen,
    toggleSidebar: state.toggleSidebar,
    setSidebarCollapsed: state.setSidebarCollapsed,
    toggleSidebarCollapsed: state.toggleSidebarCollapsed,
    openModal: state.openModal,
    closeModal: state.closeModal,
    toggleModal: state.toggleModal,
    closeAllModals: state.closeAllModals,
    addNotification: state.addNotification,
    removeNotification: state.removeNotification,
    clearNotifications: state.clearNotifications,
    setGlobalLoading: state.setGlobalLoading,
    setLoading: state.setLoading,
    clearLoading: state.clearLoading,
    setError: state.setError,
    clearError: state.clearError,
    clearAllErrors: state.clearAllErrors,
    setCurrentPage: state.setCurrentPage,
    setBreadcrumbs: state.setBreadcrumbs,
    addBreadcrumb: state.addBreadcrumb,
    setWindowFocused: state.setWindowFocused,
    setWindowVisible: state.setWindowVisible,
    reset: state.reset,
  }));

// 主题监听
useUIStore.subscribe(
  state => state.theme,
  theme => {
    const root = document.documentElement;
    if (theme === 'dark') {
      root.classList.add('dark');
    } else if (theme === 'light') {
      root.classList.remove('dark');
    } else {
      // 系统主题
      const prefersDark = window.matchMedia(
        '(prefers-color-scheme: dark)'
      ).matches;
      if (prefersDark) {
        root.classList.add('dark');
      } else {
        root.classList.remove('dark');
      }
    }
  }
);

// 系统主题变化监听
if (typeof window !== 'undefined') {
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  mediaQuery.addEventListener('change', e => {
    const { theme } = useUIStore.getState();
    if (theme === 'system') {
      const root = document.documentElement;
      if (e.matches) {
        root.classList.add('dark');
      } else {
        root.classList.remove('dark');
      }
    }
  });
}

export type { Notification, Breadcrumb };
export default useUIStore;
